package cn.com.klun.tjy.other.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * 影像接口数据获取逻辑
 * Creat by chenZ
 * 2017/10/13
 */
public class ImageService {
    public static final int POST = 1;
    public static final int GET = 2;

    private static Logger logger = LoggerFactory.getLogger(ImageService.class);

    /**
     * 根据http请求获取响应数据
     * @param ip
     * @param port
     * @param url
     * @param params
     * @param type
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static String getMessage(String ip, int port, String url, Map<String, Object> params, int type) throws IOException, UnsupportedEncodingException {
        String ret = "";
        String fullUrl = "http://" + ip + ":" + port + "/" + url;
        if (type == GET) {
            StringBuilder bb = new StringBuilder(fullUrl);
            Set<Map.Entry<String, Object>> entry = params.entrySet();
            int k = 0;
            for (Map.Entry<String, Object> e : entry) {
                k++;
                if (k == 1)
                    bb.append("?");
                else
                    bb.append("&");
                bb.append(e.getKey() + "=" + URLEncoder.encode(URLEncoder.encode(e.getValue().toString(), "utf-8"), "utf-8"));
            }
            fullUrl = bb.toString();
        }
        logger.info("请求地址：{},请求参数：{},请求方式：",fullUrl,params,type==1?"POST":"GET");
        //新建请求
        URL connUrl = new URL(fullUrl);
        //打开连接
        HttpURLConnection conn = (HttpURLConnection) connUrl.openConnection();
        //支持数据写入（传入数据）
        conn.setDoInput(true);
        //连接超时3秒（超过3秒不再连接）
        conn.setConnectTimeout(3000);
        //读写超时3秒（超过不再写入数据）
        conn.setReadTimeout(3000);
        Set<Map.Entry<String, Object>> entry = params.entrySet();
        StringBuilder builder = new StringBuilder();
        if (type==POST) {//post请求要开启一个输出流输出参
            //数，get请求只需要在请求地址中拼接参数
            //支持数据写出（传出数据）
            conn.setDoOutput(true);
            //post请求不能有缓存
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            OutputStream out = conn.getOutputStream();
            PrintWriter write = new PrintWriter(new OutputStreamWriter(out, "utf-8"), true);
            for (Map.Entry<String, Object> e : entry) {
                builder.append("&").append(e.getKey()).append("=").append(URLEncoder.encode(URLEncoder.encode(e.getValue().toString(), "utf-8"), "utf-8"));//双层encode可以解决乱码问//题，接收时再decode一下就可以了
            }
            write.append(builder);
            write.flush();
            InputStream in = conn.getInputStream();//真正的传数据过去，并且返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
            String r;
            while ((r = reader.readLine()) != null) {
                ret = r;
            }
            write.close();
            in.close();
        } else if (type == GET) {
            conn.setRequestMethod("GET");
            conn.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String s;
            if ((s = reader.readLine()) != null) {
                ret = s;
            }
            reader.close();
        }
        return ret;
    }

    //根据json字符串获取供应链数据
    public static List<Map<String,String>> getGylData(String jsonStr){
        List<Map<String,String>> datas = new ArrayList<Map<String, String>>();
        JSONArray jsonArrs = JSONArray.fromObject(jsonStr);
        ListIterator listIterator = jsonArrs.listIterator();
        while(listIterator.hasNext()){
            JSONObject next = (JSONObject) listIterator.next();
            Object typeCode = next.get("typeCode");
            Object typeName = next.get("typeName");
            Object reqUrl = next.get("reqUrl");
            if (reqUrl != null && !reqUrl.equals("")) {
               Map<String,String> data = new HashMap<String, String>();
               data.put("typeCode",typeCode.toString());
               data.put("typeName",typeName.toString());
               data.put("reqUrl",reqUrl.toString());
               datas.add(data);
            }
        }
        return datas;
    }

    //根据json字符串获取车房分借数据
    public static List<Map<String,String>> getCffjData(String jsonStr){
        List<Map<String,String>> datas = new ArrayList<Map<String, String>>();
        JSONArray jsonArrs = JSONArray.fromObject(jsonStr);
        ListIterator listIterator = jsonArrs.listIterator();
        while(listIterator.hasNext()){
            JSONObject next = (JSONObject) listIterator.next();
            Object typeCode = next.get("typeCode");
            Object typeName = next.get("typeName");
            JSONArray picList = (JSONArray) next.get("picList");
            if (picList != null && picList.size()>0) {
                ListIterator pics = picList.listIterator();
                while(pics.hasNext()){
                    JSONObject pic = (JSONObject) pics.next();
                    Object imgurl = pic.get("imgurl");
                    if (imgurl != null && !imgurl.equals("")) {
                        Map<String,String> data = new HashMap<String, String>();
                        data.put("typeCode",typeCode.toString());
                        data.put("typeName",typeName.toString());
                        data.put("reqUrl", imgurl.toString());
                        datas.add(data);
                    }
                }
            }
        }
        return datas;
    }

    public static void main(String[] args) throws IOException {
        //http://10.143.113.10:8080/gsfp-manager/service/enterprise_file/view
        Map<String,Object> params = new HashMap<String, Object>();
        params.put("contNo","JK201709190000017");
        String message = getMessage("10.143.113.10", 8080, "gsfp-manager/service/enterprise_file/view", params, POST);
        System.out.println(getGylData(message));
    }
}



